package com.yqg.demo.task;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author suzhuang
 * @ClassName: TalkReceive
 * @Function: TODO 医保系统接受数据
 * @Date: 2023/5/9 20:41
 */
@Data
@Slf4j
public class TalkybReceive implements Runnable {
    DatagramSocket socket = null;
    private int Port;
    private String msgFrom;
    private String ipAddress;
    private String sendIpAddress;
    private String message;

    public TalkybReceive(String msgFrom, int port,String sendIpAddress) {
        this.msgFrom = msgFrom;
        this.Port = port;
        this.sendIpAddress =sendIpAddress;
        try {
            socket = new DatagramSocket(Port);//开放端口
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                //准备接收
                byte[] data = new byte[1024];
                DatagramPacket packet = new DatagramPacket(data, 0, data.length);
                socket.receive(packet);    //接收数据包
                InetAddress address = packet.getAddress();
                ipAddress = String.valueOf(address);
                //过滤byte数组中的空白位置
                int k = 0;
                for (byte dataum : data) {
                    if (dataum != (byte) 0) {
                        k++;
                    }
                }
                //断开连接
                byte[] datas = packet.getData();
                String receivedata = new String(datas, 0, k);
                message = receivedata;
                //发送到内网
                sendDatatonw(this.sendIpAddress);
                log.info("发送请求到内网程序："+message);
                if(receivedata.equals("bye")){
                    break;    //监测到结束指令
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }

    /**
     * 发送数据到内网唤起医保设备
     */
    private void sendDatatonw(String nwIpAddress){
        String message="getybinfo";
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();    //建立套接字   124.167.249.190
            byte[] datas = message.getBytes(StandardCharsets.UTF_8);
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(nwIpAddress,8765));
            socket.send(packet);    //发送数据包
            log.info(nwIpAddress+","+new Date()+"发送消息："+ message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

